<?php
/**
 * 防重复提交中间件(用于风险程度较高的接口)
 * panglishan
 * 2020.09.23
 */

namespace App\Http\Middleware;

use Closure;
use App\Exceptions\BasicException;
use Illuminate\Http\Response;


class ApiLockMiddleware
{

    public function handle($request, Closure $next)
    {

        //防止重复提交(暂定2s内只能够执行一次)

        $alias = 'api_lock:'.$this->getApiAlias($request->path()).':'.UID;
        //原子操作
        $lock_detail = app('redis')->set($alias,1,'ex',2,'nx');
        if(!$lock_detail) throw new BasicException(10007);
        
//        $lock_detail = app('redis')->get($alias);
//        if(!empty($lock_detail)) throw new BasicException(10007);
//        app('redis')->setex($alias,2,1);

        return $next($request);

    }


    //限定接口的别名
    public function getApiAlias($path)
    {
        $pathArr = [
            'api/order/create' => 'create',
            'api/order/refuse' => 'refuse',
            'api/order/cancel' => 'cancel',
            'api/order/refund/agree' => 'agree',
            'api/order/settlement' => 'settlement',
            'web/ninth_activity/getcard' => 'getcard',
            'web/ninth_activity/getaward' => 'getaward',
            'api/micro_blog/create' => 'microblog',
            'api/micro_blog/like' => 'microlike',
            'api/micro_blog/comment' => 'microcomment',
            'api/micro_blog/comment/like' => 'microcommentlike',
            'api/micro_blog/like/cancel' => 'microlikecancel'
        ];

        return isset($pathArr[$path]) ? $pathArr[$path] : '';
    }

}
